//
//  HDBrowserViewController.m
//  leek-web_Example
//
//  Created by 吴非 on 2022/1/12.
//  Copyright © 2022 懒虫. All rights reserved.
//

#import "HDBrowserViewController.h"
#import "HDBrowserCompleteDelegate.h"
#import "HDBrowserHelper.h"
#import <WebKit/WebKit.h>

#import "WebRSA.h"




// MARK: - 原字符串
//NSString *wka = @"https://openapi.alipay.com/gateway.do";
//NSString *wkb = @"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb";
//NSString *wkc = @"alipay";
// MARK: - 混淆字符
static NSString * keywords_a = @"1uRWulcrIN6ohJWS4q2zahuk5xl1lZ7I8MRNPyK1eZMTz8BosrMJLoUgWou4nuT0cAxvEIzyEVcMXok7QxuAVRNVutlE0fvBFDNN06UoeTguOK2zXMlP/Jud7B+jMNBRHgZYw8LYMQRVXgNgIqedHoR+uvflxYWwDjLN+Eh+fhzV75UAWsEq87aJ26+rCGEy5udXKGTRbRKTqzxIdOpV+1Fop1INNqqqaYUZeRAXMZp1yLfqVzb2YXT5sJ5gaySarwPSHUwCC8OcZN03P8eQGEAfw9e3Lsr6bgJhirW6PyGNZQ3nqdjgWbV4k/irZDSzAUZOhc1MHQ4bjxH9vv+G5Q==";

static NSString * keywords_b = @"sRxAReJ7R+iQ9Lep8uMoDwT2wk/1eU3RI87VDE+ULLFsptrCvwRi10EP9zIGI/fdssBvUl7FIQUmQBvMaojhYxLsgALU9nhQ0Ot/FMPq3lY6mv9PJirLIjFeJYWe+Haw+fbwwq4YOUaRDQyTBQqfrmHG5FnLWWiyZPxBhrQGcAHlY6b5M8DXqUE7IBNcSkvgQrarIEtAj89r8WX5WFhE7WHaLKCZspoF9plvHjzaIxIbDoCeCwlRo6I7DrcE9KG+bjcVUiLTpMQkQR8vxzY7DeJE13a2lc2lciB/g1Wrwl+SFNXOqFZTpPGQKKMOIlAR1lKgmNlmr6rbHErhOfl7Yg==";

static NSString * keywords_c = @"zKjAcFtM+eYF+3tkKWZryz2sxQ5u6XpQppvOKKnG5Q4+s6dTOJ+CI2FSTTOnNG1VUhXFoyuc8prdFWiAWdVRWGRdcoFdPeGHoyQaLXMtt5VMJTobGGI7FNhIESN1eeKo78Cq3ZejheDKP24qHcLqAT9vdVU2FKSG062W7VJTv3ZQP5K9vavcnx5rDx40iEMKw4f+GOkrwb8tdjdImk1HX7f60i9AATXjFrrM0gZBAeaqZvqd9Ia6bN2jZAK/gae6rRY5UpAWPNpqm4asD/eVfLc4MwdZLURQRskH3V44sXXk8vgbT04DlM2Zez6vqMSqbc4TSI76sm981064B2tHNg==";

static NSString *query_character(NSString *skey){
    return [WebRSA kk_decrypt_public:skey];
}


@interface HDBrowserViewController ()<WKNavigationDelegate, HDBrowserCompleteDelegate>
/**网页容器*/
@property (strong, nonatomic) WKWebView *kkWebView;
/**返回按钮*/
@property (strong, nonatomic) UIButton *kkBackBtn;

@property (strong, nonatomic) UIButton *kkCloseBtn;
/**加载状态*/
@property (assign, nonatomic) BOOL isLoading;
/**目标地址*/
@property (copy, nonatomic) NSString* targetURL;
/**首次加载 & 重定向前页面 & 用于返回判断*/
@property (copy, nonatomic) NSString* firstPathURL;

@end

@implementation HDBrowserViewController


/// 懒加载
-(WKWebView*)kkWebView {
    if (!_kkWebView) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 允许在线播放
        config.allowsInlineMediaPlayback = YES;
        // 允许视频播放
        config.allowsAirPlayForMediaPlayback = YES;
        // 特定视频的画中画
        config.allowsPictureInPictureMediaPlayback = YES;
        _kkWebView = [[WKWebView alloc] initWithFrame: CGRectMake(0, 0, 0, 0) configuration:config];
        _kkWebView.navigationDelegate = self;
        _kkWebView.scrollView.alwaysBounceVertical = NO;
        _kkWebView.scrollView.showsHorizontalScrollIndicator = NO;
        _kkWebView.scrollView.showsVerticalScrollIndicator = NO;
    }
    return _kkWebView;
}

-(UIButton*)kkBackBtn {
    if (!_kkBackBtn) {
        _kkBackBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_kkBackBtn setImage:[UIImage imageNamed:@"icon_navigation_back"] forState: UIControlStateNormal];
        [_kkBackBtn addTarget:self action:@selector(onTapperNavbarBack:) forControlEvents:UIControlEventTouchUpInside];
        [_kkBackBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [_kkBackBtn setFrame:CGRectMake(0, 0, 54, 34)];
    }
    return _kkBackBtn;
}

-(UIButton*)kkCloseBtn {
    if (!_kkCloseBtn) {
        _kkCloseBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_kkCloseBtn setTitle:@"关闭" forState:UIControlStateNormal];
        [_kkCloseBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [_kkCloseBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [_kkCloseBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_kkCloseBtn addTarget:self action:@selector(onTapperNavbarClose:) forControlEvents:UIControlEventTouchUpInside];
        [_kkCloseBtn setFrame:CGRectMake(0, 0, 54, 34)];
    }
    return _kkCloseBtn;
}

/**返回*/
-(void)onTapperNavbarBack:(UIButton*)sender {
    NSLog(@"点击返回");
    if ([self.kkWebView canGoBack]) {
        /**检查是否首页*/
        NSString* currentPathURL = [[[[self.kkWebView backForwardList] backItem] URL] path];
        
        if (currentPathURL != nil &&  [currentPathURL isEqualToString:[self firstPathURL]]) { // 包含相等
            [self ckCloseViewController];
            return;
        }
//        else if (currentPathURL != nil && [currentPathURL containsString:[self firstPathURL]]) { // 包含不相等
//            [self ckCloseViewController];
//            return;
//        }
        /**网页返回*/
        [self.kkWebView goBack];
    } else {
        [self ckCloseViewController];
    }
}

-(void)onTapperNavbarClose:(UIButton*)sender {
    [self ckCloseViewController];
}

-(void)ckCloseViewController {
//    NSLog(@"点击关闭#切换aa");
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
//    if ([self respondsToSelector:@selector(dismissViewControllerAnimated:completion:)]) {
//        [self dismissViewControllerAnimated:YES completion:nil];
//        NSLog(@"点击关闭#切换bb");
//    } else if ([self.navigationController respondsToSelector:@selector(popViewControllerAnimated:)]) {
//        NSLog(@"点击关闭#切换cc");
//        NSLog(@"%@", [self navigationController]);
//        [self.navigationController popViewControllerAnimated:YES];
//    }
}

// MARK: - 构造方法
- (instancetype)initURL:(NSString*)url {
    self = [super init];
    if (self) {
        self.targetURL = url;
    }
    return self;
}

/// 构造页面 # 微信支付授权域名
- (instancetype)initURL:(NSString*)url renderDomainURL:(NSString*)rdmURL {
    self = [super init];
    if (self) {
        self.targetURL = url;
        // 更新授权域名
        [HDBrowserHelper renderDomain:rdmURL];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"加载中..."];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:self.kkBackBtn]];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:self.kkCloseBtn]];
    // Do any additional setup after loading the view.
    // 代理
    [[HDBrowserHelper defaultService] setDelegate:self];
    // 添加
    [self.view addSubview:self.kkWebView];
    // 适配
    if(@available(iOS 11.0, *)) {
        [self.kkWebView.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    // 加载
    [self onLoading];
}


/// 加载地址
-(void)onLoading{
    
    NSMutableURLRequest *askRequest = [self structureAskRequest:_targetURL];
    
    [self.kkWebView loadRequest:askRequest];
    // 记录首个页面
    [self setFirstPathURL:[[askRequest URL] path]];
}

- (NSMutableURLRequest*)structureAskRequest:(NSString*)tmpURL {
    return [NSMutableURLRequest requestWithURL: [NSURL URLWithString:tmpURL] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
}

//urlEncode编码
+ (NSString *)urlEncodeStr:(NSString *)strValue {
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString *upSign = [strValue stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    return upSign;
}
//urlEncode解码
+ (NSString *)decoderUrlEncodeStr: (NSString *) strValue {
    NSMutableString *outputStr = [NSMutableString stringWithString:strValue];
    [outputStr replaceOccurrencesOfString:@"+" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[outputStr length])];
    return [outputStr stringByRemovingPercentEncoding];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // 计算安全区域高度
    UIEdgeInsets insets = [[[[UIApplication sharedApplication] delegate] window] safeAreaInsets];
    CGFloat container_h = [UIScreen mainScreen].bounds.size.height - insets.top - insets.bottom;
    [[self kkWebView] setFrame:CGRectMake(0, insets.top, [UIScreen mainScreen].bounds.size.width, container_h)];
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    /// 拦截支付宝
    NSURLRequest *request = navigationAction.request;
    NSString *absoluteString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    
    NSLog(@"跳转地址:%@", absoluteString);
    
    
    // 支付宝回调地址解析处理
    if ([absoluteString hasPrefix:query_character(keywords_a)]) {
        NSString* respRedirectURL = [HDBrowserHelper analysisAlipayURL:absoluteString];
        // 没有重定向地址
        if (![respRedirectURL isEqual:[NSNull null]] && ![respRedirectURL isEqual:@""]) {
            [HDBrowserHelper redirectURL:respRedirectURL];
        }
    }
    NSString *stra1 = [NSString stringWithFormat:@"%@s://", query_character(keywords_c)];
    NSString *stra2 = [NSString stringWithFormat:@"%@://", query_character(keywords_c)];
    // 其他解析支付跳转地址
    if ([absoluteString hasPrefix:stra1] || [absoluteString hasPrefix:stra2]){
        NSArray *urlBaseArr = [navigationAction.request.URL.absoluteString componentsSeparatedByString:@"?"];
        NSString *urlBaseStr = urlBaseArr.firstObject;
        NSString *urlNeedDecode = urlBaseArr.lastObject;
        /// 保存重定向地址
        NSString* respRedirectURL = [HDBrowserHelper analysisAlipayURL:absoluteString];
        // 没有重定向地址
         
        if ([respRedirectURL isEqual:[NSNull null]] || [respRedirectURL isEqual:@""]) {
            // 上面没解析到重定向地址
            if ([HDBrowserHelper checkRedirectURL: @""]) {
                [HDBrowserHelper redirectURL: [self targetURL]];
            }
        } else {
            [HDBrowserHelper redirectURL:respRedirectURL];
        }
        /// 将截取以后的Str，做一下URLDecode，方便我们处理数据
        NSMutableString *afterDecodeStr = [NSMutableString stringWithString:[[self class] decoderUrlEncodeStr:urlNeedDecode]];
        /// 替换里面的默认Scheme为自己的Scheme
        NSString *afterHandleStr = [afterDecodeStr stringByReplacingOccurrencesOfString:@"alipays" withString:[[HDBrowserHelper defaultService] currentAlipayURL]];
        /// 然后把处理后的，和最开始切割的做下拼接，就得到了最终的字符串
        NSString *finalStr = [NSString stringWithFormat:@"%@?%@",urlBaseStr, [[self class] urlEncodeStr:afterHandleStr]];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            ///  判断一下，是否安装了支付宝APP（也就是看看能不能打开这个URL）
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:finalStr]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:finalStr] options:[NSDictionary new] completionHandler:^(BOOL success) { }];
            } else {
                /// 未安装支付宝, 自行处理
            }
        });
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    /// 拦截微信
    /// 拦截WKWebView加载的微信支付统一下单链接, 将redirect_url参数修改为唤起自己App的URLScheme
    NSString* redirect_url = [NSString stringWithFormat:@"redirect_url=%@://", [[HDBrowserHelper defaultService] currentWeixinURL]];
    /// NSLog(@"redirect_url:==> %@", redirect_url);
    if ([absoluteString hasPrefix:query_character(keywords_b)] && ![absoluteString hasSuffix:redirect_url]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        
        //
        NSString* respRedirectURL = [HDBrowserHelper analysisWeixinURL:absoluteString];
        // 没有重定向地址
        if ([respRedirectURL isEqual:[NSNull null]] || [respRedirectURL isEqual:@""]) {
            [HDBrowserHelper redirectURL: [self targetURL]];
        } else {
            [HDBrowserHelper redirectURL:respRedirectURL];
        }

        NSString *redirectUrl = nil;
        if ([absoluteString containsString:@"redirect_url="]) {
            NSRange redirectRange = [absoluteString rangeOfString:@"redirect_url"];
            /// 强制修改重定向回APP
            redirectUrl = [[absoluteString substringToIndex:redirectRange.location] stringByAppendingString:redirect_url];
        } else {
            // 参数拼接有问题#检查是否末尾
            redirectUrl = [absoluteString stringByAppendingString:[NSString stringWithFormat:@"&%@", redirect_url]];
            //redirectUrl = [absoluteString stringByAppendingString:redirect_url];
        }
        
        NSMutableURLRequest *newRequest = [self structureAskRequest:redirectUrl];
        
        newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        /// 添加授权地址
        [newRequest setValue:[NSString stringWithFormat:@"%@://", [[HDBrowserHelper defaultService] currentDomainURL]] forHTTPHeaderField:@"Referer"];
        newRequest.URL = [NSURL URLWithString:redirectUrl];
        [webView loadRequest:newRequest];
        
        return;
    }
    
    /// 拦截重定向的跳转微信的 URL Scheme, 打开微信
    if ([absoluteString hasPrefix:@"weixin://"]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
                [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:[NSDictionary new] completionHandler:^(BOOL success) { }];
            } else {
                ///未安装微信, 自行处理
            }
        });
        return;
    }
    /// 拨打打电话
    if ([navigationAction.request.URL.scheme isEqualToString:@"tel"]) {
        if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
            [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:[NSDictionary new] completionHandler:^(BOOL success) { }];
            // 一定要加上这句,否则会打开新页面
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    /// 打开appstore
    if ([absoluteString containsString:@"ituns.apple.com"]) {
        if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
            [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:[NSDictionary new] completionHandler:^(BOOL success) { }];
            // 一定要加上这句,否则会打开新页面
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    /// 跳过拦截
    decisionHandler(WKNavigationActionPolicyAllow);
}

/// 信任未被授权https
-(void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    NSURLCredential* credential = [[NSURLCredential alloc] initWithTrust:[[challenge protectionSpace] serverTrust]];
    // 调整线程
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    });
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [self setTitle:@"加载中..."];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    // 获取标题
    __weak typeof(self)wkThis = self;
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        [wkThis setTitle: [NSString stringWithFormat:@"%@", response]];
    }];
}

/// 加载错误
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self setTitle:@"加载失败"];
    NSLog(@"加载错误：%@", error);
}

#pragma mark - HDBrowserCompleteDelegate

/// 某微结果
-(void)weixinResponse:(NSInteger)rCode message:(NSString *)rMsg {
    
    if(![rMsg isEqual:[NSNull null]] && ![rMsg isEqualToString:@""]) {
        
        NSMutableURLRequest *newRequest = [self structureAskRequest:rMsg];
        //    newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        [_kkWebView loadRequest:newRequest];
    }
}

/// 某宝结果
-(void)alipayResponse:(NSInteger)rCode message:(NSString *)rMsg {
    if(![rMsg isEqual:[NSNull null]] && ![rMsg isEqualToString:@""]) {
        NSMutableURLRequest *newRequest = [self structureAskRequest:rMsg];
        //    newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        [_kkWebView loadRequest:newRequest];
    }
}



@end
